package com.cavy.platform.server.service;

import com.cavy.platform.server.CavyConfig;
import com.cavy.platform.server.domain.Pipeline;
import com.cavy.platform.server.domain.Stage;
import com.cavy.platform.server.domain.job.PendingJob;
import com.cavy.platform.server.dto.*;
import com.cavy.platform.server.mapper.PipelineMapper;
import com.cavy.platform.server.mapper.StageMapper;
import com.cavy.platform.server.repository.JobRepository;
import com.cavy.platform.server.repository.PipelineRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 唐旭
 * @Date 2018/7/18
 */
@Service
public class PipelineService {
    @Autowired
    private PipelineRepository repository;
    @Autowired
    private JobRepository jobRepository;
    @Autowired
    private JobSender jobSender;
    @Autowired
    private CavyConfig config;

    public void create(PipelineCreateDto dto) {
        repository.create(PipelineMapper.INSTANCE.convert(dto));
    }

    public void delete(PipelineDeleteDto dto) {
        repository.delete(PipelineMapper.INSTANCE.convert(dto));
    }

    public List<PipelineDto> list(PipelineSearchDto dto) {
        List<Pipeline> pipelineList = repository.list(dto);
        List<PipelineDto> pipelineDtos = new ArrayList<>(pipelineList.size());
        for (Pipeline pipeline : pipelineList) {
            pipelineDtos.add(PipelineMapper.INSTANCE.toDto(pipeline));
        }
        return pipelineDtos;
    }

    //1,根据类型创建标准步骤/组步骤
    //2,根据插件对数据进行验证
    //3,处理步骤的依赖
    public void addStage(StageAddDto dto) {
        Pipeline pipeline = repository.find(dto.getWorkspace(), dto.getProjectName(), dto.getPipeline());
        //将dto 转换为domain
        Stage stage = StageMapper.INSTANCE.toDomain(dto);
        pipeline.addStage(stage);
    }

    public void deleteStage(StageDeleteDto dto) {
        Pipeline pipeline = repository.find(dto.getWorkspace(), dto.getProjectName(), dto.getPipeline());
        pipeline.removeStage(dto.getName());
    }

    public PipelineDto info(PipelineGetInfoDto dto) {
        Pipeline pipeline = repository.find(dto.getWorkspace(), dto.getProjectName(), dto.getPipeline());
        return PipelineMapper.INSTANCE.toDto(pipeline);
    }

    public void modifyStage(StageModifyDto dto) {
        Pipeline pipeline = repository.find(dto.getWorkspace(), dto.getProjectName(), dto.getPipeline());
        Stage stage = pipeline.findStage(dto.getStageName());
        StageMapper.INSTANCE.toDomain(dto, stage);
        repository.save(pipeline);
    }

    public String run(PipelineRunDto dto) {
        Pipeline pipeline = repository.find(dto.getWorkspace(), dto.getProjectName(), dto.getPipelineName());
        PendingJob job = pipeline.jobBuild(config.getJob());
        jobRepository.save(job);
        jobSender.send(job);
        return job.getJob().getNumber();
    }
}
